package com.zx.bus.controller;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zx.bus.domain.Customer;
import com.zx.bus.service.CustomerService;
import com.zx.bus.service.RentService;
import com.zx.bus.vo.RentVo;
import com.zx.sys.constast.SysConstast;
import com.zx.sys.domain.User;
import com.zx.sys.utils.DataGridView;
import com.zx.sys.utils.RandomUtils;
import com.zx.sys.utils.ResultObj;
import com.zx.sys.utils.WebUtils;

@RestController
@RequestMapping("rent")
public class RentController {
	
	@Autowired
	private RentService rentService;
	
	@Autowired
	private CustomerService customerService;
	
	@RequestMapping("loadAllRent")
	public DataGridView loadAllRent(RentVo rentVo){
		return rentService.queryAllRent(rentVo);
	}
	
	@RequestMapping("checkCustomerExist")
	public ResultObj checkCustomerExist(RentVo rentVo){
		Customer customer = customerService.queryCustomerByIdentity(rentVo.getIdentity());
		if(customer!=null){
			return new ResultObj(SysConstast.CODE_SUCCESS);
		}else{
			return new ResultObj(SysConstast.CODE_ERROR);
		}
	}
	
	@RequestMapping("initRentFrom")
	public RentVo initRentFrom(RentVo rentVo){
		rentVo.setRentid(RandomUtils.createRandomStringUseTime("CZ"));
		rentVo.setBegindate(new Date());
		
		User user = (User) WebUtils.getHttpSession().getAttribute("user");
		rentVo.setOpername(user.getRealname());
		return rentVo;
	}
	
	@RequestMapping("saveRent")
	public ResultObj saveRent(RentVo rentVo){
		try {
			rentVo.setCreatetime(new Date());
			rentVo.setRentflag(SysConstast.RENT_BACK_FALSE);
			
			rentService.addRent(rentVo);
			return new ResultObj(SysConstast.CODE_SUCCESS,SysConstast.ADD_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			return new ResultObj(SysConstast.CODE_ERROR,SysConstast.ADD_ERROR);
		}
	}
	
	@RequestMapping("updateRent")
	public ResultObj updateRent(RentVo rentVo) {
		try {
			rentService.updateRent(rentVo);
			return new ResultObj(SysConstast.CODE_SUCCESS,SysConstast.UPDATE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResultObj(SysConstast.CODE_ERROR,SysConstast.UPDATE_ERROR);
		}
	}
	
	@RequestMapping("deleteRent")
	public ResultObj deleteRent(RentVo rentVo){
		try {
			rentService.deleteRent(rentVo.getRentid());
			return new ResultObj(SysConstast.CODE_SUCCESS,SysConstast.DELETE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResultObj(SysConstast.CODE_ERROR,SysConstast.DELETE_ERROR);
		}
	}
}
